package com.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis-plus全局配置
 */
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //添加分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MetaObjectHandler() {
            //执行插入语句时要自动填充的字段值
            @Override
            public void insertFill(MetaObject metaObject) {
                this.setFieldValByName("createDate", LocalDateTime.now(),metaObject);
                this.setFieldValByName("updateDate",LocalDateTime.now(),metaObject);
                this.setFieldValByName("delFlag","0",metaObject);
            }

            //执行更新语句时要自动填充的字段值
            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateDate",LocalDateTime.now(),metaObject);
            }
        };
    }
}
